package ge.telasi.tasks.ui.task;

import ge.telasi.tasks.ejb.TaskFacadeRemote;
import ge.telasi.tasks.model.Task;
import ge.telasi.tasks.model.User;
import ge.telasi.tasks.ui.Platform;
import ge.telasi.tasks.ui.UIUtils;
import ge.telasi.tasks.ui.comp.CommonDialog;
import ge.telasi.tasks.ui.log.LoggerUtils;
import java.awt.Component;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

/**
 * @author dimitri
 */
public class NewTaskDialog extends CommonDialog {
    private static final long serialVersionUID = 597914825423500717L;

    public NewTaskDialog(Component parent) {
        super(parent, true);
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        subjectAndBodyPanel = new ge.telasi.tasks.ui.task.NewTaskSubjectAndBodyPanel();
        taskReceiverPanel = new ge.telasi.tasks.ui.task.NewTaskReceiverPanel();
        priorityPanel = new ge.telasi.tasks.ui.task.PriorityPanel();
        attachmentPanel = new ge.telasi.tasks.ui.task.AttachmentPanel();
        taskRelationPanel = new ge.telasi.tasks.ui.task.TaskRelationPanel();
        btnSend = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        logger = new ge.telasi.tasks.ui.log.InlineLogger();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("ახალი დავალება");

        jTabbedPane1.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);

        subjectAndBodyPanel.setLogger(logger);
        jTabbedPane1.addTab("ძირითადი", new javax.swing.ImageIcon(getClass().getResource("/ge/telasi/resorces/icons16x16/email.png")), subjectAndBodyPanel, "ძირითადი თვისებები"); // NOI18N

        taskReceiverPanel.setLogger(logger);
        jTabbedPane1.addTab("შემსრულებლები", new javax.swing.ImageIcon(getClass().getResource("/ge/telasi/resorces/icons16x16/group.png")), taskReceiverPanel, "დავალების შემსრულებელთა სია"); // NOI18N

        priorityPanel.setLogger(logger);
        jTabbedPane1.addTab("პრიორიტეტი", new javax.swing.ImageIcon(getClass().getResource("/ge/telasi/resorces/icons16x16/clock.png")), priorityPanel, "დავალების პრიორიტეტი და შესრულების ვადა"); // NOI18N

        attachmentPanel.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                attachmentPanelPropertyChange(evt);
            }
        });
        jTabbedPane1.addTab("ფაილები", new javax.swing.ImageIcon(getClass().getResource("/ge/telasi/resorces/icons16x16/attach.png")), attachmentPanel, "დავალების დოკუმენტური მასალა"); // NOI18N

        taskRelationPanel.setParent(true);
        jTabbedPane1.addTab("საფუძველი", new javax.swing.ImageIcon(getClass().getResource("/ge/telasi/resorces/icons16x16/feed.png")), taskRelationPanel, "დავალების საფუძველი"); // NOI18N

        btnSend.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ge/telasi/resorces/icons16x16/email.png"))); // NOI18N
        btnSend.setText("გაგზავნა");
        btnSend.setToolTipText("დავალების გაგზავნა");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ge/telasi/resorces/icons16x16/disk.png"))); // NOI18N
        btnSave.setText("შენახვა");
        btnSave.setToolTipText("დავალების შენახვა");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnSave)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 477, Short.MAX_VALUE)
                .addComponent(btnSend)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(logger, javax.swing.GroupLayout.DEFAULT_SIZE, 646, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(logger, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnSend))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        onSend(false);
    }//GEN-LAST:event_btnSendActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        onSend(true);
    }//GEN-LAST:event_btnSaveActionPerformed

    private void attachmentPanelPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_attachmentPanelPropertyChange
        attachmentPanel.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                if ("task".equals(evt.getPropertyName())) {
                    task = (Task) evt.getNewValue();
                    resetAttachments();
                    fireTaskChange();
                }
            }
        });
    }//GEN-LAST:event_attachmentPanelPropertyChange

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private ge.telasi.tasks.ui.task.AttachmentPanel attachmentPanel;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSend;
    private javax.swing.JTabbedPane jTabbedPane1;
    private ge.telasi.tasks.ui.log.InlineLogger logger;
    private ge.telasi.tasks.ui.task.PriorityPanel priorityPanel;
    private ge.telasi.tasks.ui.task.NewTaskSubjectAndBodyPanel subjectAndBodyPanel;
    private ge.telasi.tasks.ui.task.NewTaskReceiverPanel taskReceiverPanel;
    private ge.telasi.tasks.ui.task.TaskRelationPanel taskRelationPanel;
    // End of variables declaration//GEN-END:variables

    private boolean approved;
    private Task task;

    protected boolean valiadateForm(boolean saveAsDraft) {
        subjectAndBodyPanel.clearLogger();
        priorityPanel.clearLogger();
        taskReceiverPanel.clearLogger();
        if (!saveAsDraft) {
            if (!subjectAndBodyPanel.validateForm()) {
                jTabbedPane1.setSelectedIndex(0);
                return false;
            }
            if (!taskReceiverPanel.validateForm()) {
                jTabbedPane1.setSelectedIndex(1);
                return false;
            }
            if (!priorityPanel.validateForm()) {
                jTabbedPane1.setSelectedIndex(2);
                return false;
            }
        }
        return true;
    }

    private Task getFormTask() {
        Task formTask = new Task();
        if (task != null) {
            formTask.setId(task.getId());
        }
        subjectAndBodyPanel.fillTask(formTask);
        taskReceiverPanel.fillTask(formTask);
        priorityPanel.fillTask(formTask);
        formTask.getParents().addAll(taskRelationPanel.getRelations());
        formTask.setAttachments(attachmentPanel.getAttachments());
        return formTask;
    }

    private void onSend(boolean saveAsDraft) {
        Platform pl = Platform.getDefault();
        if (pl.validateConnection() && valiadateForm(saveAsDraft)) {
            try {
                // get facade
                TaskFacadeRemote facade = pl.getFacade();

                // for user
                User forUser = null;

                // determine whether show ForUser dialog
                boolean showForUserDialog = false;
                showForUserDialog = saveAsDraft && task == null;
                if (!showForUserDialog && task != null && saveAsDraft) {
                    boolean isOwner = task.getOwner().equals(pl.getUser());
                    boolean isPreparedBy = task.getPreparedBy().equals(pl.getUser());
                    if (isPreparedBy) {
                        showForUserDialog = true;
                    }
                }

                // select for whom task should be prepared
                if (showForUserDialog) {
                    PrepareTaskForDialog prepareDialog = new PrepareTaskForDialog(this);
                    prepareDialog.setMainUser(pl.getUser());
                    if (task != null) {
                        prepareDialog.setOwnerUser(task.getOwner());
                    }
                    UIUtils.openDialog(prepareDialog);
                    if (!prepareDialog.isApproved()) {
                        return;
                    }
                    forUser = prepareDialog.getUser();
                }
                // get forUser from task
                else if (task != null) {
                    forUser = task.getOwner();
                }
                task = facade.createTask(pl.getCredentials(), getFormTask(), forUser, saveAsDraft);
                approved = true;
                dispose();
            } catch (Exception ex) {
                LoggerUtils.manageException(this, ex);
            }
        }
    }

    public boolean isApproved() {
        return approved;
    }

    public Task getTask() {
        return task;
    }

    public void setTask(Task task) {
        this.task = task;
        resetTask();
    }

    private void resetTask() {
        // subject and body
        subjectAndBodyPanel.setSubject(task.getSubject());
        subjectAndBodyPanel.setBody(task.getLastBody());
        subjectAndBodyPanel.setStructure(task.getStructure());

        // receiver panel
        taskReceiverPanel.setAssignees(task.getAssignees());
        taskReceiverPanel.setCopies(task.getCopies());

        // relation
        taskRelationPanel.setRelations(task.getParents(), true);

        // priority
        priorityPanel.setTask(task);

        // attachment
        resetAttachments();
    }

    protected void fireTaskChange() {
        firePropertyChange("task", "dummy string as old value", task);
    }

    protected void resetAttachments() {
        attachmentPanel.setTask(task);
    }
    
}
